#include "InputMapping.h"
#include <QStringList>

InputMapping::InputMapping(const ButtonMap &buttonMap, const AxisMap &axisMap)
  : mButtonMap(buttonMap),
    mAxisMap(axisMap)
{
}

int InputMapping::axisValue(const HalfAxisType& hat, int value) const
{
  int ret(0);
  foreach(AxisType at, mAxisMap)
  {
    if (at.mNeg == hat)
    {
      if (hat.mDirection == HalfAxisType::DIRECTION_POS)
      {
        ret = -value;
      }
      else
      {
        ret = value;
      }
    }
    else if (at.mPos == hat)
    {
      if (hat.mDirection == HalfAxisType::DIRECTION_POS)
      {
        ret = value;
      }
      else
      {
        ret = -value;
      }
    }
  }
  return ret;
}

int InputMapping::axisValue(const QString& name, const HalfAxisType& hat, int value) const
{
  int ret(0);
  AxisType at(mAxisMap.value(name));
  if (at.mNeg == hat)
  {
    if (hat.mDirection == HalfAxisType::DIRECTION_POS)
    {
      ret = -value;
    }
    else
    {
      ret = value;
    }
  }
  else if (at.mPos == hat)
  {
    if (hat.mDirection == HalfAxisType::DIRECTION_POS)
    {
      ret = value;
    }
    else
    {
      ret = -value;
    }
  }
  return ret;
}

QString InputMapping::axisName(const HalfAxisType& hat) const
{
  QString ret;
  AxisMap::const_iterator it;
  for (it = mAxisMap.begin(); it != mAxisMap.end(); ++it)
  {
    if (it.value().mNeg == hat || it.value().mPos == hat)
    {
      ret = it.key();
    }
  }
  return ret;
}

QStringList InputMapping::axisNames(const HalfAxisType& hat) const
{
  QStringList ret;
  AxisMap::const_iterator it;
  for (it = mAxisMap.begin(); it != mAxisMap.end(); ++it)
  {
    if (it.value().mNeg == hat || it.value().mPos == hat)
    {
      ret.push_back(it.key());
    }
  }
  return ret;
}

void InputMapping::press(const ButtonType &bt)
{
  QStringList names(mButtonMap.keys(bt));

  HalfAxisType hat;
  hat.mType = HalfAxisType::TYPE_BUTTON;
  hat.mButton = bt;
  movement(hat, 100);

  foreach(QString name, names)
  {
    emit buttonPress(name);
  }
}

void InputMapping::release(const ButtonType &bt)
{
  QStringList names(mButtonMap.keys(bt));

  HalfAxisType hat;
  hat.mType = HalfAxisType::TYPE_BUTTON;
  hat.mButton = bt;
  movement(hat, 0);

  foreach(QString name, names)
  {
    emit buttonRelease(name);
  }
}

void InputMapping::movement(const HalfAxisType &hat, int value)
{
  QStringList names(axisNames(hat));
  foreach(QString name, names)
  {
    value = axisValue(name, hat, value);
    emit axisMovement(name, value);
  }
}
